package logic

import (
	"bw-renting/common"
	"context"
	"errors"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"net/http"

	"bw-renting/api/internal/svc"
	"bw-renting/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPayNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayNotifyLogic {
	return &PayNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayNotifyLogic) PayNotify(req *types.PayNotifyReq, r *http.Request, w http.ResponseWriter) error {
	// todo: add your logic here and delete this line

	r.ParseForm()
	fmt.Println(11111)
	// DecodeNotification 内部已调用 VerifySign 方法验证签名
	var noti, err = common.Client.DecodeNotification(r.Form)
	fmt.Println(22222)
	if err != nil {
		// 错误处理
		fmt.Println(err)
		return nil
	}
	switch noti.TradeStatus {
	case alipay.TradeStatusSuccess: //（交易支付成功）
		// 处理成功后返回 success
		fmt.Println("success")
		return nil
	case alipay.TradeStatusClosed:
		err = errors.New("未付款交易超时关闭，或支付完成后全额退款")
	case alipay.TradeStatusFinished:
		err = errors.New("交易结束，不可退款")
	case alipay.TradeStatusWaitBuyerPay:
		err = errors.New("交易创建，等待买家付款")
	}
	// 业务处理
	// 如果通知消息没有问题，我们需要确认收到通知消息，不然支付宝后续会继续推送相同的消息
	alipay.ACKNotification(w)

	return nil
}
